<template>
	<view class="container">
		<view class="shop">
			<view>
				<text>付款给 {{seller_info.seller_name}}</text>
				<!-- <image src="../../static/images/public/yinlianColor.png" mode=""></image> -->
			</view>
			<image :src="seller_info.logo" mode=""></image>
		</view>
		<view class="payable">
			<text class="title">消费金额</text>
			<input v-model="payable" placeholder-style="font-size:30rpx;font-weight:normal" type="digit" placeholder="请输入付款金额" />
			<view class="doller">￥</view>
		</view>
		<view class="actuallyPaid">
			<text class="title">实付金额</text>
			<view class="num">
				<text>￥</text>
				<text>{{actuallyPaid}}</text>
			</view>
		</view>
		<view class="deduction">
			<view class="cell">
				<view class="left">
					<text v-if="seller_info.shop_commission_retrun_mode == 1">本次消费可获得黑贝壳</text>
					<text v-if="seller_info.shop_commission_retrun_mode == 2">本次消费可获得积分</text>
				</view>
				<view class="right">
					<image v-if="seller_info.shop_commission_retrun_mode == 1" src="../../static/images/public/shellIcon.png" mode=""></image>
					<text class="num">+{{backShell}}</text>
				</view>
			</view>
			<view v-for="(item,index) in shellList" :key="index">
				<view class="cell">
					<view class="left">
						<text>{{item.name||''}}抵扣</text>
					</view>
					<evan-switch :size="18" active-color="#57BE6A" :disabled="item.disabled" v-model="item.checked" @change="shellSwitch(item)"></evan-switch>
				</view>
				<view class="cell">
					<view class="left label">
						<text>共{{item.available_count||''}}</text>
						<text v-if="item.checked">,使用{{item.shellDeduction||''}},抵￥{{item.shellDeduction*item.rate||''}}</text>
					</view>
					<view v-if="item.checked&&item.available_count !== '0.00'" class="right" @tap="!item.disabled&&shellChange()">
						<text class="change">修改</text>
					</view>
				</view>
			</view>

			<view class="cell">
				<view class="left">
					<text>余额抵扣</text>
				</view>
				<evan-switch :size="18" active-color="#57BE6A" :disabled="userAccountInfo.now_money == 0" v-model="yueChecked"></evan-switch>
			</view>
			<view class="cell">
				<view class="left label">
					<text>余额</text>
					<text>共￥{{userAccountInfo.now_money||''}}</text>
					<text v-if="yueChecked">，使用￥{{yueDeduction||''}}，抵￥{{yueDeduction||''}}</text>
				</view>
				<view v-if="yueChecked&&userAccountInfo.now_money !== '0.00'" class="right" @tap="yueChange()">
					<text class="change">修改</text>
				</view>
			</view>
		</view>
		<view class="btn" @tap="submit">付款</view>
		<uni-popup ref="shellChange" type="center">
			<view class="box">
				<image @tap="close" src="../../static/images/center/close.png" mode=""></image>
				<view class="title">{{shellItem.name}}抵扣</view>
				<view class="content">
					<view class="label">
						<text>拥有{{shellItem.name}}</text>
						<text>{{shellItem.available_count}}</text>
					</view>
					<view class="inputBox">
						<text>使用{{shellItem.name}}</text>
						<text>个</text>
						<input type="digit" v-model="shellItem.shellDeduction" @input="shellChanged" />
					</view>
					<view class="inputBox">
						<text>可抵扣</text>
						<text>元</text>
						<input disabled="true" type="text" v-model="shellItem.shellDeduction*shellItem.rate" />
					</view>
					<view @tap="close" class="btn">确认</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="yueChange" type="center">
			<view class="box">
				<image @tap="close" src="../../static/images/center/close.png" mode=""></image>
				<view class="title">余额抵扣</view>
				<view class="content">
					<view class="label">
						<text>拥有余额</text>
						<text>{{userAccountInfo.now_money}}</text>
					</view>
					<view class="inputBox">
						<text>使用余额</text>
						<text>元</text>
						<input type="digit" v-model="yueDeduction" @input="yueChanged" />
					</view>
					<view @tap="close" class="btn">确认</view>
				</view>
			</view>
		</uni-popup>
		<!-- app选择支付方式 -->
		<choosePay ref="choosePay" @confirm="confirm"></choosePay>
		<!-- 抵扣全部金额输入平台操作密码 -->
		<passkeyborad :show="keyboradShow" @close="keyboradClose" @finish="finished"></passkeyborad>
		<view class="cover" v-if="cover"></view>
		<!-- 支付宝支付 -->
		<view v-html='orderForm'></view>
	</view>
</template>

<script>
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import evanSwitch from "@/components/evan-switch/evan-switch.vue"
	import utils from "@/common/utils.js"
	import passkeyborad from '@/components/yzc-paykeyboard/yzc-paykeyboard.vue'
	import {
		sellerPayDetail,
		sellerPay
	} from "@/api/pay.js"
	import {
		shellList
	} from "@/api/shell.js"
	import {
		checkPassword
	} from "@/api/user.js"
	import wechat from '@/common/wechat.js'
	import choosePay from '@/components/choosePay/choosePay.vue'
	export default {
		components: {
			evanSwitch,
			uniPopup,
			passkeyborad,
			choosePay
		},
		data() {
			return {
				payable: '', //应支付金额
				provider: "wxpay",
				payType: "weixin",
				shellList: [{
						shellDeduction: 0
					},
					{
						shellDeduction: 0
					},
					{
						shellDeduction: 0
					},
					{
						shellDeduction: 0
					}
				], // 贝壳列表
				yueChecked: false, //余额抵扣开关
				yueDeduction: 0, //余额使用数量
				data: {}, // url数据
				shellItemChange: { // 贝壳抵扣开关切换
					checked: false,
					id: -1
				},
				shellItem: {
					shellDeduction: 0,
					rate: 0
				}, // 选中要修改的贝壳数据
				seller_info: {}, // 商户数据
				share_mode: "",//商户分享模式
				userAccountInfo: {}, // 个人数据
				ration: "", // 返贝壳率
				option: {}, // 支付码携带参数
				cover: true, // 遮罩层
				keyboradShow: false, //操作密码键盘显示/隐藏
				orderForm: "" //支付宝h5支付返回的form表单
			}
		},
		onLoad(options) {
			//#ifdef H5
			var ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/micromessenger/i) == 'micromessenger') {
				// 微信h5支付
				this.payType = "weixin"
			} else if (ua.match(/Alipay/i) == "alipay") {
				// 支付宝h5支付
				this.payType = "alipay"
			}
			//#endif
			if (options.scene && !uni.getStorageSync("Authori-zation")) {
				this.option = utils.urlDecode(options)
				//#ifdef H5
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let curRoute = "/" + routes[routes.length - 1].route //获取当前页面路由
				let curParam = routes[routes.length - 1].options; //获取路由参数
				// 拼接参数
				let param = ''
				for (let key in curParam) {
				    param += '&' + key + '=' + curParam[key]
				}
				param = param.substr(1)
				let QRCodeRout = curRoute + "?" + param
				uni.setStorageSync("QRCodeRout", QRCodeRout)
				//#endif
				uni.setStorageSync("pid", this.option.uid)
				uni.setStorageSync("pos", this.option.uk)
			} else if (options.scene && uni.getStorageSync("Authori-zation")) {
				this.option = utils.urlDecode(options)
			} else if (options.uid && options.uk && !uni.getStorageSync("Authori-zation")) {
				this.option = options
				//#ifdef H5
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let curRoute = "/" + routes[routes.length - 1].route //获取当前页面路由
				let curParam = routes[routes.length - 1].options; //获取路由参数
				// 拼接参数
				let param = ''
				for (let key in curParam) {
				    param += '&' + key + '=' + curParam[key]
				}
				param = param.substr(1)
				let QRCodeRout = curRoute + "?" + param
				uni.setStorageSync("QRCodeRout", QRCodeRout)
				//#endif
				uni.setStorageSync("pid", options.uid)
				uni.setStorageSync("pos", options.uk)
			} else if (options.uid && options.uk && uni.getStorageSync("Authori-zation")) {
				this.option = options
			} else if (options.id) {
				this.option.sid = options.id
			}

		},
		onShow() {
			this.data = this.option
			sellerPayDetail({
				seller_id: this.data.sid
			}).then(res => {
				if (res.data.status) {
					return uni.showModal({
						content: res.msg,
						confirmText: "去首页",
						confirmColor: "#57be6a",
						showCancel: false,
						success(re) {
							if (re.confirm) {
								uni.navigateTo({
									url: "/pages/index/index?current=0"
								})
							}
						}
					})
				}
				shellList().then(res => {
					this.shellList = res.data.shell_list.map((val, key) => {
						val.checked = false
						val.shellDeduction = 0
						if (val.available_count == 0) {
							val.disabled = true
						} else {
							val.disabled = false
						}
						return val
					});
				})
				this.seller_info = res.data.seller_info
				this.share_mode = res.data.share_mode
				this.userAccountInfo = res.data.userAccountInfo
				this.ration = Number(res.data.personal_shell_ration)
				this.cover = false
			})

		},
		computed: {
			// 计算应付现金
			actuallyPaid() {
				let needPay = (Number(this.payable) - Number(this.yueDeduction) - Number(this.shellItem.shellDeduction) * Number(
					this.shellItem.rate)).toFixed(2)
				return needPay
			},
			// 计算可获得贝壳
			backShell() {
				let backShell = parseInt(Number(this.payable) * Number(this.ration) * 100) / 100
				return backShell
			}
		},
		watch: {
			yueChecked: {
				deep: true,
				handler(val, oldval) {
					this.yueCheckeChange();
				}
			},
			shellItemChange: {
				deep: true,
				handler(val, oldval) {
					this.shellCheckeChange();
				}
			},
			payable: {
				deep: true,
				handler(val, oldval) {
					this.changePayable();
				}
			}
		},
		methods: {
			changePayable() {
				this.shellList = this.shellList.map((val, key) => {
					val.checked = false
					val.shellDeduction = 0
					this.shellItemChange = {
						checked: false,
						id: -1
					}
					return val
				});
				this.yueChecked = false
				this.yueDeduction = 0
			},
			// 控制只能使用一种贝壳抵扣
			shellSwitch(item) {
				this.shellItem = item
				this.shellItemChange.checked = item.checked
				this.shellItemChange.id = item.id
				let _this = this
				if (item.checked) {
					_this.shellList.forEach((items, index) => {
						if (item.id !== items.id) {
							_this.shellList[index].disabled = true
						}
					})
				} else {
					_this.shellList.forEach((items, index) => {
						_this.shellList[index].disabled = false
					})
				}
			},
			//改变贝壳抵扣开关
			shellCheckeChange() {
				let _this = this
				if (this.shellItem.checked) {
					if (Number(this.shellItem.available_count) > Number((Number(this.payable) - this.yueDeduction).toFixed(2))) {
						this.shellItem.shellDeduction = Number((Number(this.payable) - this.yueDeduction).toFixed(2))
					} else {
						this.shellItem.shellDeduction = Number(this.shellItem.available_count)
					}

				} else {
					this.shellItem.shellDeduction = 0
				}
			},
			// 打开修改贝壳抵扣面板
			shellChange() {
				this.$refs.shellChange.open()
			},
			// 修改贝壳抵扣数量
			shellChanged() {
				let _this = this
				this.$nextTick(function() {
					this.shellItem.shellDeduction = utils.verifyNum(this.shellItem.shellDeduction)
				})
				let totalPrice = Number(this.payable)
				if (Number((totalPrice - this.yueDeduction).toFixed(2)) > Number(this.shellItem.available_count)) {
					if (Number(this.shellItem.shellDeduction) > Number(this.shellItem.available_count)) {
						this.$nextTick(function() {
							uni.showToast({
								icon: "none",
								title: "不能超过可用贝壳数"
							})
							this.shellItem.shellDeduction = Number(this.shellItem.available_count)
						})
					}
				} else {
					if (Number(this.shellItem.shellDeduction) > Number((totalPrice - this.yueDeduction).toFixed(2))) {
						this.$nextTick(function() {
							uni.showToast({
								icon: "none",
								title: "不能超过需支付金额"
							})
							this.shellItem.shellDeduction = Number((totalPrice - this.yueDeduction).toFixed(2))
						})
					}
				}
			},
			//改变余额抵扣开关
			yueCheckeChange() {
				if (this.yueChecked) {
					if (Number(this.userAccountInfo.now_money) > Number((Number(this.payable) - Number(this.shellItem.shellDeduction))
							.toFixed(2))) {
						this.yueDeduction = Number((Number(this.payable) - Number(this.shellItem.shellDeduction)).toFixed(2))
					} else {
						this.yueDeduction = Number(this.userAccountInfo.now_money)
					}
				} else {
					this.yueDeduction = 0
				}
			},
			// 打开修改余额抵扣面板
			yueChange() {
				this.$refs.yueChange.open()
			},
			// 修改抵扣余额
			yueChanged() {
				let _this = this
				this.$nextTick(function() {
					this.yueDeduction = utils.verifyNum(this.yueDeduction)
				})
				let totalPrice = Number(this.payable)
				if ((totalPrice - Number(this.shellItem.shellDeduction)).toFixed(2) > Number(this.userAccountInfo.now_money)) {
					if (Number(this.yueDeduction) > Number(this.userAccountInfo.now_money)) {
						this.$nextTick(function() {
							uni.showToast({
								icon: "none",
								title: "不能超过可用余额"
							})
							this.yueDeduction = Number(this.userAccountInfo.now_money)
						})
					}
				} else {
					if (Number(this.yueDeduction) > Number((totalPrice - this.shellItem.shellDeduction).toFixed(2))) {
						this.$nextTick(function() {
							uni.showToast({
								icon: "none",
								title: "不能超过需支付金额"
							})
							this.yueDeduction = Number((totalPrice - this.shellItem.shellDeduction).toFixed(2))
						})
					}
				}
			},
			close() {
				this.$refs.shellChange.close()
				this.$refs.yueChange.close()
			},
			submit() {
				if (this.payable == 0 || this.payable == '') {
					return uni.showToast({
						icon: "none",
						title: "请输入消费金额"
					})
				}
				if (this.actuallyPaid == 0) {
					if (!uni.getStorageSync("userInfo").withdraw_pass) {
						uni.showModal({
							content: "0元支付需设置操作密码",
							confirmText: "去设置",
							cancelText: "取消",
							confirmColor: "#57BE6A",
							success(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: "/pages/center/accountSet/payPassword/payPassword?backurl=true"
									})
								} else if (res.cancel) {}

							}
						})
						return
					}
					this.keyboradShow = true
				} else {
					//#ifndef APP-PLUS
					this.submitPay()
					//#endif
					//#ifdef APP-PLUS
					this.$refs.choosePay.show()
					//#endif
				}
			},
			finished(password) {
				uni.showLoading({
					mask:true
				})
				checkPassword({
					password: password
				}, this.keyboradClose()).then(res => {
					this.submitPay()
				})
			},
			confirm(e) {
				this.payType = e.payType
				this.provider = e.provider
				this.submitPay()
			},
			keyboradClose() {
				this.keyboradShow = false
			},
			submitPay() {
				uni.showLoading({
					mask:true
				})
				sellerPay({
					total_price: this.payable,
					mer_id: this.data.sid,
					now_money: this.yueDeduction,
					// use_conch: this.shellDeduction,
					black_shell_num: this.shellList[0].shellDeduction,
					yellow_shell_num: this.shellList[1].shellDeduction,
					red_shell_num: this.shellList[2].shellDeduction,
					blue_shell_num: this.shellList[3].shellDeduction,
					useIntegral: "",
					couponId: "",
					payType: this.payType,
					// #ifdef MP-WEIXIN
					from: "routine",
					// #endif
					// #ifdef APP-PLUS
					from: "app",
					// #endif
					// #ifdef H5
					from: "",
					// #endif
				}).then(res => {
					uni.hideLoading()
					if (res.data.status == "ZERO_SUCCESS") {
						uni.showToast({
							title: "支付成功"
						})
						//#ifdef H5
						var ua = window.navigator.userAgent.toLowerCase();
						if (ua.match(/micromessenger/i) == 'micromessenger') {
							// 微信h5支付
							if (res.data.result.shop_commission_retrun_mode == 1) {
								uni.redirectTo({
									url: "/pages/order/orderDetail?id=" + res.data.result.orderId
								})
							} else {
								uni.redirectTo({
									url: "/pages/public/jifenShare?id=" + res.data.result.orderId + "&fen=" + res.data.result.user_get_integral + "&share_mode=" + this.share_mode
								})
							}
						} else if (ua.match(/Alipay/i) == "alipay") {
							// 支付宝h5支付
							uni.redirectTo({
								url: "/pages/order/orderDetail?id=" + res.data.result.orderId
							})
						}
						//#endif
						//#ifndef H5
						if (res.data.result.shop_commission_retrun_mode == 1) {
							uni.redirectTo({
								url: "/pages/order/orderDetail?id=" + res.data.result.orderId
							})
						} else {
							uni.redirectTo({
								url: "/pages/public/jifenShare?id=" + res.data.result.orderId + "&fen=" + res.data.result.user_get_integral + "&share_mode=" + this.share_mode
							})
						}
						//#endif
					} else {
						// #ifdef MP-WEIXIN
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: res.data.result.jsConfig.timestamp,
							nonceStr: res.data.result.jsConfig.nonceStr,
							package: res.data.result.jsConfig.package,
							signType: res.data.result.jsConfig.signType,
							paySign: res.data.result.jsConfig.paySign,
							success: function(re) {
								if (res.data.result.shop_commission_retrun_mode == 1) {
									uni.redirectTo({
										url: "/pages/order/orderDetail?id=" + res.data.result.orderId
									})
								} else {
									uni.redirectTo({
										url: "/pages/public/jifenShare?id=" + res.data.result.orderId + "&fen=" + res.data.result.user_get_integral + "&share_mode=" + this.share_mode
									})
								}
							},
							fail: function(err) {
								console.log(err)
							}
						});
						// #endif
						// #ifdef APP-PLUS
						uni.requestPayment({
							provider: this.provider,
							orderInfo: res.data.result.jsConfig,
							success: function(re) {
								if (res.data.result.shop_commission_retrun_mode == 1) {
									uni.redirectTo({
										url: "/pages/order/orderDetail?id=" + res.data.result.orderId
									})
								} else {
									uni.redirectTo({
										url: "/pages/public/jifenShare?id=" + res.data.result.orderId + "&fen=" + res.data.result.user_get_integral + "&share_mode=" + this.share_mode
									})
								}
							},
							fail: function(err) {
								console.log(err)
							}
						})
						// #endif
						//#ifdef H5
						var ua = window.navigator.userAgent.toLowerCase();
						if (ua.match(/micromessenger/i) == 'micromessenger') {
							// 微信h5支付
							let url = ""
							if (res.data.result.shop_commission_retrun_mode == 1) {
								url = "/pages/order/orderDetail?id=" + res.data.result.orderId
							} else {
								url = "/pages/public/jifenShare?id=" + res.data.result.orderId + "&fen=" + res.data.result.user_get_integral + "&share_mode=" + this.share_mode
							}
							wechat.pay(res.data.result.jsConfig, url, false)
						} else if (ua.match(/Alipay/i) == "alipay") {
							// 支付宝h5支付
							this.orderForm = res.data.result.jsConfig
							this.$nextTick(function() {
								document.forms['alipaysubmit'].submit()
							})
						}
						//#endif
					}
				})
			}
		}
	}
</script>
<style lang="scss">
	page {
		min-height: 100vh;
		background-color: #f5f5f5;
	}
</style>
<style lang="scss" scoped>
	.container {
		.shop {
			background-color: #fff;
			padding: 20rpx 30rpx;
			display: flex;
			justify-content: space-between;

			view {
				display: flex;
				flex-direction: column;
				justify-content: center;

				text {
					font-size: 32rpx;
					font-weight: bold;
					color: rgba(17, 17, 17, 1);
				}

				image {
					margin-top: 6rpx;
					width: 40rpx;
					height: 26rpx;
				}
			}

			>image {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50rpx;
			}
		}

		.payable {
			background-color: #fff;
			padding: 30rpx;
			position: relative;

			.title {
				font-size: 27rpx;
				font-weight: 600;
				color: rgba(51, 51, 51, 1);
			}

			input {
				padding-left: 50rpx;
				margin-top: 10rpx;
				border-bottom: 1rpx solid #eee;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 53rpx;
				font-weight: bold;
				color: #333;
			}

			.doller {
				position: absolute;
				left: 30rpx;
				bottom: 46rpx;
				font-weight: bold;
				font-size: 40rpx;
				color: #333;
			}
		}

		.actuallyPaid {
			padding: 70rpx 45rpx;

			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: rgba(51, 51, 51, 1);
			}

			.num {
				padding: 30rpx 0;
				display: flex;
				justify-content: center;
				align-items: flex-end;
				vertical-align: text-bottom;

				text:nth-of-type(1) {
					font-size: 53rpx;
					font-weight: 600;
					color: rgba(51, 51, 51, 1);
				}

				text:nth-of-type(2) {
					font-size: 107rpx;
					line-height: 107rpx;
					font-weight: 600;
					color: rgba(17, 17, 17, 1);
				}
			}
		}

		.deduction {
			padding: 20rpx 0;
			width: 690rpx;
			margin-left: 30rpx;
			background-color: #fff;
			border-radius: 14rpx;

			.cell {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 20rpx;
				height: 66rpx;
				line-height: 66rpx;

				.left {
					text {
						font-size: 26rpx;
						font-weight: bold;
						color: rgba(51, 51, 51, 1);
					}
				}

				.label {
					text {
						font-size: 22rpx !important;
					}
				}

				.right {
					image {
						width: 33rpx;
						height: 24rpx;
						margin-right: 6rpx;
					}

					.num {
						font-size: 26rpx;
						font-weight: bold;
						color: $theme-color;
					}

					.change {
						display: block;
						font-size: 16rpx;
						color: rgba(51, 51, 51, 1);
						width: 59rpx;
						height: 24rpx;
						line-height: 24rpx;
						border-radius: 12rpx;
						text-align: center;
						background-color: #e5e5e5;
					}
				}

				.switch {
					width: 50rpx;
					height: 50rpx;
				}
			}
		}

		.btn {
			width: 690rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: $theme-color;
			color: #fff;
			font-size: 32rpx;
			font-weight: bold;
			border-radius: 40rpx;
			margin: 60rpx 30rpx;
		}
	}

	.box {
		background-color: #fff;
		position: relative;
		width: 600rpx;
		padding: 36rpx;
		box-sizing: border-box;
		border-radius: 10rpx;

		image {
			position: absolute;
			top: 40rpx;
			right: 40rpx;
			width: 26rpx;
			height: 26rpx;
		}

		.title {
			text-align: center;
			font-size: 32rpx;
			font-weight: bold;
		}

		.content {
			.label {
				display: flex;
				justify-content: center;
				font-size: 28rpx;
				color: #333;
				margin-top: 46rpx;
				align-items: center;

				text:nth-of-type(2) {
					margin-left: 8rpx;
					font-weight: bold;
				}
			}

			.inputBox {
				position: relative;
				height: 114rpx;
				line-height: 114rpx;
				border-bottom: 1rpx solid #eee;

				text:nth-of-type(1) {
					font-size: 28rpx;
					position: absolute;
					top: 0;
					left: 0;
				}

				text:nth-of-type(2) {
					font-size: 28rpx;
					position: absolute;
					top: 0;
					right: 0;
				}

				input {
					height: 114rpx;
					text-align: right;
					padding-right: 58rpx;
					font-size: 56rpx;
				}
			}

			.btn {
				margin: 40rpx 0 0;
				width: 528rpx;
				height: 80rpx;
				background: $theme-color;
				border-radius: 40rpx;
			}
		}

	}

	.cover {
		position: fixed;
		left: 0;
		top: 0;
		height: 100%;
		width: 100%;
		background-color: #fff;
		z-index: 99999999;
	}
</style>
